import { useState } from 'react'
import './rydj.scss'
import { LeftOutline, CalendarOutline } from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom'

// 日期选择器组件
const DatePickerComponent = ({ onDateSelect }: { onDateSelect: (date: string) => void }) => {
    const currentYear = new Date().getFullYear()
    const [selectedYear, setSelectedYear] = useState(currentYear - 30)
    const [selectedMonth, setSelectedMonth] = useState(1)
    const [selectedDay, setSelectedDay] = useState(1)

    const years = Array.from({ length: 100 }, (_, i) => currentYear - i)
    const months = Array.from({ length: 12 }, (_, i) => i + 1)
    const days = Array.from({ length: 31 }, (_, i) => i + 1)

    const handleConfirm = () => {
        const date = `${selectedYear}/${selectedMonth.toString().padStart(2, '0')}/${selectedDay.toString().padStart(2, '0')}`
        onDateSelect(date)
    }

    return (
        <div className='date-picker-content'>
            <div className='date-selectors'>
                <div className='date-selector'>
                    <label>年</label>
                        <select
                            value={selectedYear}
                            onChange={(e) => setSelectedYear(parseInt(e.target.value))}
                        >
                            {years.map(year => (
                                <option key={year} value={year}>{year}</option>
                            ))}
                        </select>
                </div>
                <div className='date-selector'>
                    <label>月</label>
                        <select
                            value={selectedMonth}
                            onChange={(e) => setSelectedMonth(parseInt(e.target.value))}
                        >
                            {months.map(month => (
                                <option key={month} value={month}>{month}</option>
                            ))}
                        </select>
                </div>
                <div className='date-selector'>
                    <label>日</label>
                        <select
                            value={selectedDay}
                            onChange={(e) => setSelectedDay(parseInt(e.target.value))}
                        >
                            {days.map(day => (
                                <option key={day} value={day}>{day}</option>
                            ))}
                        </select>
                </div>
            </div>
            <div className='date-picker-actions'>
                <button className='cancel-btn' onClick={() => onDateSelect('')}>取消</button>
                <button className='confirm-btn' onClick={handleConfirm}>确定</button>
            </div>
        </div>
    )
}

function Rydj() {
    const navigate = useNavigate()
    const [formData, setFormData] = useState({
        patientName: '',
        age: '',
        gender: '女',
        birthDate: '2020/01/01',
        idNumber: '',
        medicalCardNumber: '',
        phoneNumber: '',
        nationality: '',
        ethnicity: '',
        currentAddress: '',
        currentAddressDetail: '',
        householdAddress: '',
        householdAddressDetail: '',
        contactName: '',
        contactPhone: '',
        contactRelationship: '',
        contactAddress: '',
        contactAddressDetail: ''
    })

    // 添加验证错误状态
    const [errors, setErrors] = useState<{ [key: string]: string }>({})
    const [isSubmitting, setIsSubmitting] = useState(false)
    const [showDatePicker, setShowDatePicker] = useState(false)

    // 验证规则函数
    const validateField = (field: string, value: string): string => {
        switch (field) {
            case 'patientName':
                if (!value.trim()) return '请输入患者姓名'
                if (value.trim().length < 2) return '姓名至少需要2个字符'
                return ''

            case 'age':
                if (!value.trim()) return '请输入年龄'
                {
                    const age = parseInt(value)
                    if (isNaN(age) || age < 0 || age > 150) return '请输入有效的年龄(0-150)'
                }
                return ''

            case 'gender':
                if (!value) return '请选择性别'
                return ''

            case 'birthDate':
                if (!value || value === '2020/01/01') return '请选择出生日期'
                return ''

            case 'idNumber':
                if (!value.trim()) return '请输入身份证号'
                {
                    const idRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
                    if (!idRegex.test(value)) return '请输入正确的身份证号格式'
                }
                return ''

            case 'medicalCardNumber':
                if (!value.trim()) return '请输入就诊卡号'
                if (value.trim().length < 6) return '就诊卡号至少需要6位'
                return ''

            case 'phoneNumber':
                if (!value.trim()) return '请输入本人电话'
                {
                    const phoneRegex = /^1[3-9]\d{9}$/
                    if (!phoneRegex.test(value)) return '请输入正确的手机号格式'
                }
                return ''

            case 'currentAddress':
                if (!value.trim()) return '请选择现住址'
                return ''

            case 'currentAddressDetail':
                if (!value.trim()) return '请输入现住址详情'
                if (value.trim().length < 5) return '现住址详情至少需要5个字符'
                return ''

            case 'contactName':
                if (!value.trim()) return '请输入联系人姓名'
                if (value.trim().length < 2) return '联系人姓名至少需要2个字符'
                return ''

            case 'contactPhone':
                if (!value.trim()) return '请输入联系人电话'
                {
                    const contactPhoneRegex = /^1[3-9]\d{9}$/
                    if (!contactPhoneRegex.test(value)) return '请输入正确的联系人手机号格式'
                }
                return ''

            default:
                return ''
        }
    }

    const handleInputChange = (field: string, value: string) => {
        setFormData(prev => ({
            ...prev,
            [field]: value
        }))

        // 实时验证
        const error = validateField(field, value)
        setErrors(prev => ({
            ...prev,
            [field]: error
        }))
    }

    // 处理日期选择
    const handleDateSelect = (date: string) => {
        handleInputChange('birthDate', date)
        setShowDatePicker(false)
    }


    // 验证所有必填字段
    const validateAllFields = (): boolean => {
        const requiredFields = [
            'patientName', 'age', 'gender', 'birthDate', 'idNumber',
            'medicalCardNumber', 'phoneNumber', 'currentAddress',
            'currentAddressDetail', 'contactName', 'contactPhone'
        ]

        const newErrors: { [key: string]: string } = {}
        let isValid = true

        requiredFields.forEach(field => {
            const error = validateField(field, formData[field as keyof typeof formData])
            if (error) {
                newErrors[field] = error
                isValid = false
            }
        })

        setErrors(newErrors)
        return isValid
    }

    const handleSubmit = async () => {
        if (isSubmitting) return

        setIsSubmitting(true)

        // 验证所有字段
        if (!validateAllFields()) {
            alert('请完善必填信息后再提交')
            setIsSubmitting(false)
            return
        }

        try {
            console.log('表单数据:', formData)
            // 这里可以添加提交逻辑
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 1000))
            // 跳转到入院审核页面，传递表单数据
            navigate('/rysj', { 
                state: { 
                    formData: formData,
                    reviewTime: new Date().toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit',
                        second: '2-digit'
                    }).replace(/\//g, '-')
                } 
            })
        } catch {
            alert('提交失败，请重试')
        } finally {
            setIsSubmitting(false)
        }
    }
    return (
        <div className='rydj'>
            <div className='rydj-top'>
                <span><LeftOutline className='rydj-top-left' onClick={() => navigate(-1)} /></span>
                <span className='rydj-top-title'>入院登记</span>
            </div>
            <div className='rydj-bg'>
                <div className='progress-container'>
                    <div className='progress-step active'>
                        <div className='step-circle'>
                            <span className='step-number'>1</span>
                        </div>
                        <span className='step-label'>基本信息</span>
                    </div>
                    <div className='progress-line'></div>
                    <div className='progress-step'>
                        <div className='step-circle'>
                            <span className='step-number'>2</span>
                        </div>
                        <span className='step-label'>入院审核</span>
                    </div>
                </div>
            </div>
            <div className='rydj-content'>
                <div className='form-title'>请完善以下基本信息</div>
                    <div className='form-container'>
                        {/* 患者姓名 */}
                        <div className='form-item'>
                            <label className='form-label'>
                        姓名<span className='required'>*</span>
                        </label>
                        <input
                            type='text'
                            className={`form-input ${errors.patientName ? 'error' : ''}`}
                            placeholder='请输入姓名'
                            value={formData.patientName}
                            onChange={(e) => handleInputChange('patientName', e.target.value)}
                        />
                        {errors.patientName && (
                            <div className='error-message'>{errors.patientName}</div>
                        )}
                    </div>

                    {/* 年龄 */}
                    <div className='form-item'>
                        <label className='form-label'>
                            年龄<span className='required'>*</span>
                        </label>
                        <input
                            type='text'
                            className={`form-input ${errors.age ? 'error' : ''}`}
                            placeholder='请输入年龄'
                            value={formData.age}
                            onChange={(e) => handleInputChange('age', e.target.value)}
                        />
                        {errors.age && (
                            <div className='error-message'>{errors.age}</div>
                        )}
                    </div>

                    {/* 性别 */}
                    <div className='form-item'>
                        <label className='form-label'>
                            性别<span className='required'>*</span>
                        </label>
                        <div className='radio-group'>
                            <label className='radio-item'>
                                <input
                                    type='radio'
                                    name='gender'
                                    value='女' 
                                    checked={formData.gender === '女'}
                                    onChange={(e) => handleInputChange('gender', e.target.value)}
                                />
                                <span className='radio-text'>女</span>
                            </label>
                            <label className='radio-item'>
                                <input 
                                    type='radio' 
                                    name='gender' 
                                    value='男' 
                                    checked={formData.gender === '男'}
                                    onChange={(e) => handleInputChange('gender', e.target.value)}
                                />
                                <span className='radio-text'>男</span>
                            </label>
                        </div>
                        {errors.gender && (
                            <div className='error-message'>{errors.gender}</div>
                        )}
                    </div>

                    {/* 出生日期 */}
                    <div className='form-item'>
                        <label className='form-label'>
                            出生日期<span className='required'>*</span>
                        </label>
                        <div className='date-input-container'>
                            <input 
                                type='text' 
                                className={`form-input date-input ${errors.birthDate ? 'error' : ''}`}
                                value={formData.birthDate}
                                readOnly
                                onClick={() => setShowDatePicker(true)}
                            />
                            <CalendarOutline className='calendar-icon' onClick={() => setShowDatePicker(true)} />
                        </div>
                        {errors.birthDate && (
                            <div className='error-message'>{errors.birthDate}</div>
                        )}
                    </div>

                    {/* 身份证号 */}
                    <div className='form-item'>
                        <label className='form-label'>
                            身份证号<span className='required'>*</span>
                        </label>
                        <input 
                            type='text' 
                            className={`form-input ${errors.idNumber ? 'error' : ''}`}
                            placeholder='请输入身份证号'
                            value={formData.idNumber}
                            onChange={(e) => handleInputChange('idNumber', e.target.value)}
                        />
                        {errors.idNumber && (
                            <div className='error-message'>{errors.idNumber}</div>
                        )}
                    </div>

                    {/* 就诊卡号 */}
                    <div className='form-item'>
                        <label className='form-label'>
                            就诊卡号<span className='required'>*</span>
                        </label>
                        <input 
                            type='text' 
                            className={`form-input ${errors.medicalCardNumber ? 'error' : ''}`}
                            placeholder='请输入就诊卡号'
                            value={formData.medicalCardNumber}
                            onChange={(e) => handleInputChange('medicalCardNumber', e.target.value)}
                        />
                        {errors.medicalCardNumber && (
                            <div className='error-message'>{errors.medicalCardNumber}</div>
                        )}
                    </div>

                    {/* 本人电话 */}
                    <div className='form-item'>
                        <label className='form-label'>
                            本人电话<span className='required'>*</span>
                        </label>
                        <input 
                            type='text' 
                            className={`form-input ${errors.phoneNumber ? 'error' : ''}`}
                            placeholder='请输入本人联系电话'
                            value={formData.phoneNumber}
                            onChange={(e) => handleInputChange('phoneNumber', e.target.value)}
                        />
                        {errors.phoneNumber && (
                            <div className='error-message'>{errors.phoneNumber}</div>
                        )}
                    </div>

                    {/* 国籍 */}
                    <div className='form-item'>
                        <label className='form-label'>国籍</label>
                        <div className='select-container'>
                            <select 
                                className='form-select'
                                value={formData.nationality}
                                onChange={(e) => handleInputChange('nationality', e.target.value)}
                            >
                                <option value=''>请选择国籍</option>
                                <option value='中国'>中国</option>
                                <option value='美国'>美国</option>
                                <option value='日本'>日本</option>
                            </select>
                            <span className='select-arrow'>▼</span>
                        </div>
                    </div>

                    {/* 民族 */}
                    <div className='form-item'>
                        <label className='form-label'>民族</label>
                        <div className='select-container'>
                            <select 
                                className='form-select'
                                value={formData.ethnicity}
                                onChange={(e) => handleInputChange('ethnicity', e.target.value)}
                            >
                                <option value=''>请选择民族</option>
                                <option value='汉族'>汉族</option>
                                <option value='蒙古族'>蒙古族</option>
                                <option value='回族'>回族</option>
                            </select>
                            <span className='select-arrow'>▼</span>
                        </div>
                    </div>

                    {/* 现住址 */}
                    <div className='form-item'>
                        <label className='form-label'>
                            现住址<span className='required'>*</span>
                        </label>
                        <div className='select-container'>
                            <select 
                                className={`form-select ${errors.currentAddress ? 'error' : ''}`}
                                value={formData.currentAddress}
                                onChange={(e) => handleInputChange('currentAddress', e.target.value)}
                            >
                                <option value=''>请选择现居住地址</option>
                                <option value='北京市'>北京市</option>
                                <option value='上海市'>上海市</option>
                                <option value='广州市'>广州市</option>
                            </select>
                            <span className='select-arrow'>▼</span>
                        </div>
                        {errors.currentAddress && (
                            <div className='error-message'>{errors.currentAddress}</div>
                        )}
                    </div>

                    {/* 现住址详情 */}
                    <div className='form-item'>
                        <label className='form-label'>
                            现住址详情<span className='required'>*</span>
                        </label>
                        <input 
                            type='text' 
                            className={`form-input ${errors.currentAddressDetail ? 'error' : ''}`}
                            placeholder='请输入现住址详情,精确到门牌号'
                            value={formData.currentAddressDetail}
                            onChange={(e) => handleInputChange('currentAddressDetail', e.target.value)}
                        />
                        {errors.currentAddressDetail && (
                            <div className='error-message'>{errors.currentAddressDetail}</div>
                        )}
                    </div>

                    {/* 户口地址 */}
                    <div className='form-item'>
                        <label className='form-label'>户口地址</label>
                        <div className='select-container'>
                            <select 
                                className='form-select'
                                value={formData.householdAddress}
                                onChange={(e) => handleInputChange('householdAddress', e.target.value)}
                            >
                                <option value=''>请选择现户口地址</option>
                                <option value='北京市'>北京市</option>
                                <option value='上海市'>上海市</option>
                                <option value='广州市'>广州市</option>
                            </select>
                            <span className='select-arrow'>▼</span>
                        </div>
                    </div>

                    {/* 户口地址详情 */}
                    <div className='form-item'>
                        <label className='form-label'>户口地址详情</label>
                        <input 
                            type='text' 
                            className='form-input' 
                            placeholder='请输入户口住址详情,精确到门牌号'
                            value={formData.householdAddressDetail}
                            onChange={(e) => handleInputChange('householdAddressDetail', e.target.value)}
                        />
                    </div>

                    {/* 联系人姓名 */}
                    <div className='form-item'>
                        <label className='form-label'>
                            联系人姓名<span className='required'>*</span>
                        </label>
                        <input 
                            type='text' 
                            className={`form-input ${errors.contactName ? 'error' : ''}`}
                            placeholder='请输入联系人姓名'
                            value={formData.contactName}
                            onChange={(e) => handleInputChange('contactName', e.target.value)}
                        />
                        {errors.contactName && (
                            <div className='error-message'>{errors.contactName}</div>
                        )}
                    </div>

                    {/* 联系人电话 */}
                    <div className='form-item'>
                        <label className='form-label'>
                            联系人电话<span className='required'>*</span>
                        </label>
                        <input 
                            type='text' 
                            className={`form-input ${errors.contactPhone ? 'error' : ''}`}
                            placeholder='请输入联系人电话'
                            value={formData.contactPhone}
                            onChange={(e) => handleInputChange('contactPhone', e.target.value)}
                        />
                        {errors.contactPhone && (
                            <div className='error-message'>{errors.contactPhone}</div>
                        )}
                    </div>

                    {/* 联系人关系 */}
                    <div className='form-item'>
                        <label className='form-label'>联系人关系</label>
                        <div className='select-container'>
                            <select 
                                className='form-select'
                                value={formData.contactRelationship}
                                onChange={(e) => handleInputChange('contactRelationship', e.target.value)}
                            >
                                <option value=''>请选择联系人与患者关系</option>
                                <option value='配偶'>配偶</option>
                                <option value='子女'>子女</option>
                                <option value='父母'>父母</option>
                                <option value='兄弟姐妹'>兄弟姐妹</option>
                            </select>
                            <span className='select-arrow'>▼</span>
                        </div>
                    </div>

                    {/* 联系人地址 */}
                    <div className='form-item'>
                        <label className='form-label'>联系人地址</label>
                        <div className='select-container'>
                            <select 
                                className='form-select'
                                value={formData.contactAddress}
                                onChange={(e) => handleInputChange('contactAddress', e.target.value)}
                            >
                                <option value=''>请选择联系人地址</option>
                                <option value='北京市'>北京市</option>
                                <option value='上海市'>上海市</option>
                                <option value='广州市'>广州市</option>
                            </select>
                            <span className='select-arrow'>▼</span>
                        </div>
                    </div>

                    {/* 联系人地址详情 */}
                    <div className='form-item'>
                        <label className='form-label'>联系人地址详情</label>
                        <input 
                            type='text' 
                            className='form-input' 
                            placeholder='请输入联系人住址详情,精确到门牌号'
                            value={formData.contactAddressDetail}
                            onChange={(e) => handleInputChange('contactAddressDetail', e.target.value)}
                        />
                    </div>
                </div>

                {/* 提交按钮 */}
                <div className='submit-container'>
                    <button 
                        className={`submit-button ${isSubmitting ? 'loading' : ''}`} 
                        onClick={handleSubmit}
                        disabled={isSubmitting}
                    >
                        {isSubmitting ? '提交中...' : '提交申请'}
                    </button>
                </div>
            </div>

            {/* 日期选择器 */}
            {showDatePicker && (
                <div className='date-picker-overlay' onClick={() => setShowDatePicker(false)}>
                    <div className='date-picker' onClick={(e) => e.stopPropagation()}>
                        <div className='date-picker-header'>
                            <h3>选择出生日期</h3>
                            <button 
                                className='close-btn' 
                                onClick={() => setShowDatePicker(false)}
                            >
                                ×
                            </button>
                        </div>
                        <DatePickerComponent onDateSelect={handleDateSelect} />
                    </div>
                </div>
            )}
        </div>
    )
}

export default Rydj